package com.Jee.JeeHttp;

import com.Jee.HttpEntity.HttpRequest;
import com.Jee.HttpEntity.HttpResponse;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServerV2 {

    private ServerSocket serverSocket = null;

    public HttpServerV2(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true){
            Socket clientSocket = serverSocket.accept();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    handle(clientSocket);
                }
            });
        }
    }

    public void handle(Socket clientSocket) {
        try {
            HttpRequest request = HttpRequest.RequestBuilder(clientSocket.getInputStream());
            System.out.println("request: "+request);
            HttpResponse response = HttpResponse.ResponseBuilder(clientSocket.getOutputStream());
            response.setHeaders("Content-Type","text/html");
            response.setStatus(200);
            response.setStatusMessage("OK");
            response.writeBody("<h1>test</h1>");
            response.flush();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
